<script setup>
import {message} from 'ant-design-vue'
import {getCurrentInstance} from "vue";
import RegionChart from '~/contentScripts/views/tao/list/components/market/regionChart.vue'
import ShopTypeAnalysis from '~/contentScripts/views/tao/list/components/market/shopTypeAnalysis.vue'
import categoryAnalysis from '~/contentScripts/views/tao/list/components/market/categoryAnalysis.vue'
import priceChart from '~/contentScripts/views/tao/list/components/market/priceChart.vue';

import SoldChart from '~/contentScripts/views/tao/list/components/market/soldChart.vue'
import {categoryData, isLogin} from '~/logic'
import {batch} from '~/logic/apis/taoCategory'
import {TRequest} from '~/utils/ali/PCRequest'

const emit = defineEmits(['login'])
// 主图分析
const visible = ref(false)
const visibleShow = ref(false)
const showTitle = ref('')
// 1 综合排序 2 销量排序 3 价格升序 4 价格降序
const sortType = ref('1')
// 解析location.href 的参数
const url = location.href
const params = url.split('?')[1]
const paramsArr = params.split('&')
const paramsObj = {}
paramsArr.forEach((item) => {
  paramsObj[item.split('=')[0]] = decodeURIComponent(item.split('=')[1])
})
const searchStatus = ref(false)
const dataSources = ref([])
const keywords = ref(paramsObj.q)
const minAmount = ref('')
const maxAmount = ref('')
const number = ref(2)
const current = ref(1)
const __option = getCurrentInstance()?.appContext.provides.option;
const handle = () => {
  if (isLogin({
    emit,
  }, __option)) {
    current.value = 1
    visible.value = true
    // visibleShow.value = true
    showTitle.value = '市场分析'
  }
}
const analysis = async () => {
  current.value = 1
  // goodsNumber.value.tmall = 0
  // goodsNumber.value.taobao = 0
  // saleNumber.value.tmall = 0
  // saleNumber.value.taobao = 0
  if (!keywords.value) {
    message.error('请输入关键词!')
    return
  }
  searchStatus.value = true
  let sortTypeValue = 1
  const sortParams = {
    q: keywords.value,
    search_type: 'item',
  }
  let sortName = ''
  if (sortType.value === '1') {
    sortTypeValue = 1
    sortName = '综合排序'
  } else if (sortType.value === '2') {
    sortTypeValue = 2
    sortName = '销量排序'
  } else if (sortType.value === '4') {
    sortTypeValue = 4
    sortName = '价格降序'
  } else if (sortType.value === '5') {
    sortTypeValue = 5
    sortName = '价格升序'
  }else{
    sortTypeValue = 6
    sortName = '信任'
  }
  let startPrice = null
  let endPrice = null
  if (minAmount.value !== '') {
    startPrice = minAmount.value
  }

  if (minAmount.value !== '') {
    endPrice = maxAmount.value
  }

  Reflect.set(dataSources, 'value', [])
  showTitle.value = `星察数据_市场分析(${sortName})_${keywords.value}`

  for (; current.value <= number.value; current.value++) {
    // const cacheKey = sortParams.sort + keywords.value + sortParams.filter + i
    let res = {}
    try {
      res = await TRequest.searchList(keywords.value, current.value, sortTypeValue, startPrice, endPrice)
    } catch (e) {
      message.error('请求失败请稍后重试!')
      searchStatus.value = false
      return
    }
    if (typeof res.itemsArray === 'undefined') {
      message.error('请求失败请稍后重试!')
      searchStatus.value = false
      return
    }
    // 给itemArray注入index
    res.itemsArray.forEach((item, index) => {
      item.index = (current.value - 1) * 48 + index + 1
      item.isTmall = item.iconList.includes('tmall')
      item.link = item.iconList.includes('tmall') ? `//detail.tmall.com/item.htm?id=${item.item_id}` : `//item.taobao.com/item.htm?id=${item.item_id}`
    })
    console.log(res.itemsArray,'res.itemsArray')

    // 取出分类
    const ids = res.itemsArray.map((item) => {
      return item.leafCategory
    })

    const result = await batch(ids)
    console.log(result,'类目商品获取6666')
    dataSources.value.push(...res.itemsArray)
    console.log(dataSources,'dataSources','我是数据最新')
    visibleShow.value = true
    searchStatus.value = false
  }
  // Reflect.set(checkedImageLists, 'value', [])
}
const columns = [

  {
    title: '商品ID',
    dataIndex: 'item_id',
    key: 'item_id',
    width: 120,
    fixed: 'left',
  },
  {
    title: '商品',
    dataIndex: 'title',
    dataType: 'product',
    dataField: {
      item_title: 'title',
      item_pic: 'pic_path',
      item_id: 'item_id',
    },
    key: 'goods',
    fixed: 'left',
  },
  {
    title: '排名',
    dataIndex: 'index',
    key: 'index',
    sorter: (a, b) => a.index - b.index,
    width: 60,
    align: 'center',
  },
  {
    title: '原价',
    dataIndex: 'price',
    key: 'price',
    sorter: (a, b) => a.price - b.price,
    width: 100,
    align: 'center',
  },
  {
    title: '现价',
    dataIndex: 'priceWap',
    key: 'priceWap',
    sorter: (a, b) => a.priceWap - b.priceWap,
    width: 100,
    align: 'center',
  },
  // {
  //   title: '价格',
  //   dataIndex: 'price',
  //   key: 'price',
  //   sorter: (a, b) => a.price - b.price,
  //   width: 100,
  //   align: 'center',
  // },
  // {
  //   title: '月销',
  //   dataIndex: 'monthlySales',
  //   key: 'monthlySales',
  //   sorter: (a, b) => a.monthlySales - b.monthlySales,
  //   width: 100,
  //   align: 'center',
  // },
  // {
  //   title: '月销',
  //   dataIndex: 'sold',
  //   key: 'sold',
  //   sorter: (a, b) => a.sold - b.sold,
  //   width: 100,
  //   align: 'center',
  // },
  {
    title: '付款人数',
    dataIndex: 'realSales',
    key: 'realSales',
    dataType: 'realSales',
    sorter: (a, b) => (a.realSales.match(/\d+/)[0] || 0) - (b.realSales.match(/\d+/)[0] || 0),
    width: 100,
    align: 'center',
  },
  {
    title: '类目',
    dataIndex: 'leafCategory',
    dataType: "category",
    width: 120,
  },
  {
    title: '店铺名称',
    dataIndex: 'shopInfo.title',
    key: 'shopInfo',
    width: 120,
  },
  {
    title: '平台',
    dataIndex: 'isTmall',
    key: 'isTmall',
    dataType: 'platform',
    width: 60,
  },
  {
    title: '地址',
    dataIndex: 'procity',
    key: 'procity',
    width: 120,
  },
]
</script>

<template>
  <div @click="handle" style="display: inline-block;">
    <slot>
      <a-button type="primary" size="small" style="margin-left: 10px;">
        市场分析
      </a-button>
    </slot>
  </div>
  <a-modal v-model:visible="visible" title="市场分析" :width="600" :mask-closable="false" :footer="false">
    <a-spin :spinning="searchStatus">
      <a-form
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 20 }"
      >
        <a-form-item label="排序">
          <a-radio-group v-model:value="sortType">
            <a-radio-button value="1">
              综合排序
            </a-radio-button>
            <a-radio-button value="2">
              销量排序
            </a-radio-button>
            <a-radio-button value="4">
              价格降序
            </a-radio-button>
            <a-radio-button value="5">
              价格升序
            </a-radio-button>
            <a-radio-button value="6">
              信任
            </a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="关键词">
          <a-input v-model:value="keywords" placeholder="请输入关键词"/>
        </a-form-item>
        <a-form-item label="价格区间">
          <a-input-number v-model:value="minAmount" style="width: 120px;" placeholder="最低价" addon-after="元"/>
          ~
          <a-input-number v-model:value="maxAmount" style="width: 120px;" placeholder="最高价" addon-after="元"/>
        </a-form-item>
        <a-form-item label="搜索数量">
          前
          <a-input-number v-model:value="number" style="width: 100px;" placeholder=""/>
          页(每页48条)
        </a-form-item>
        <a-divider/>
        <div style="text-align: center;width: 80%;margin: 0 auto;">
          <a-button shape="round" block type="primary" size="large" @click="analysis">
            开始分析
          </a-button>
        </div>
      </a-form>
    </a-spin>
  </a-modal>
  <a-modal
      v-model:visible="visibleShow" style="top: 20px;max-height: calc(100vh - 100px);" :title="showTitle"
      :width="1520" :footer="false"
  >
    <a-tabs style="margin-top: -10px;" destroy-inactive-tab-pane>
      <a-tab-pane :key="1" tab="店铺类型分析">
        <ShopTypeAnalysis :data-source="dataSources"/>
      </a-tab-pane>
      <a-tab-pane :key="2" tab="地域分布">
        <RegionChart :data-source="dataSources"/>
      </a-tab-pane>
      <a-tab-pane :key="3" tab="付款人数分布">
        <SoldChart :data-source="dataSources"/>
      </a-tab-pane>
      <a-tab-pane :key="4" tab="价格分布">
        <!-- <RegionChart key="shopNumber" :data-source="dataSources" type="shopNumber"/> -->
         <priceChart :data-source="dataSources" />
      </a-tab-pane>
      <a-tab-pane :key="5" tab="类目分析">
        <categoryAnalysis :data-source="dataSources"/>
      </a-tab-pane>
    </a-tabs>
    <a-divider/>
    <base-table
        table-name="市场分析"
        size="small"
        :row-key="(_, index) => index"
        :data-source="dataSources"
        :pagination="false"
        :columns="columns"
        :scroll="{ x: 1480, y: 400 }"
    >
      <!--      <template #bodyCell="props">-->
      <!--        <a-row v-if="props.column.dataIndex === 'goods'" type="flex">-->
      <!--          <a-col>-->
      <!--            <a-image-->
      <!--              :src="props.record.pic_path"-->
      <!--              :width="20"-->
      <!--              :height="20"-->
      <!--            />-->
      <!--          </a-col>-->
      <!--          <a-col flex="1">-->
      <!--            <a type="link" :href="props.record.link" style="margin-left: 10px;">-->
      <!--              {{ props.record.title.replace(/<[^>]+>/g, '') }}-->
      <!--            </a>-->
      <!--          </a-col>-->
      <!--        </a-row>-->
      <!--        <template v-else-if="props.column.dataIndex === 'index'">-->
      <!--          {{ props.record.index }}-->
      <!--        </template>-->
      <!--        <template v-else-if="props.column.dataIndex === 'monthlySales'">-->
      <!--          - -->
      <!--        </template>-->
      <!--        <template v-else-if="props.column.dataIndex === 'leafCategory'">-->
      <!--          <span style="font-size: 14px">-->
      <!--            {{-->
      <!--              categoryData[props.record.leafCategory] ? categoryData[props.record.leafCategory].path.join('/') : '无官方类目数据'-->
      <!--            }}-->
      <!--          </span>-->
      <!--        </template>-->
      <!--        <template v-else-if="props.column.dataIndex === 'shopInfo'">-->
      <!--          <span style="font-size: 14px">-->
      <!--            {{ props.record.shopInfo.title }}-->
      <!--          </span>-->
      <!--        </template>-->
      <!--        <template v-else-if="props.column.dataIndex === 'platform'">-->
      <!--          <span style="font-size: 14px">-->
      <!--            {{ props.record.isTmall ? '天猫' : '淘宝' }}-->
      <!--          </span>-->
      <!--        </template>-->
      <!--      </template>-->
    </base-table>
    <a-divider style="margin: 0 0 10px;"/>
    <div style="color: #444;">
      已加载商品数量：{{ dataSources.length }}
    </div>
  </a-modal>
</template>

<style scoped>

</style>
